package com.example.finger.socket;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.finger.FingerHelper;
import com.example.finger.bean.LockLog;
import com.example.finger.bean.SoketOrder;
import com.google.gson.Gson;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.FileUtils;
import com.lyxmaster.lib.util.SharedPreferencesHelper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LYX on 2018/11/14.
 */

public class ThreadReadWriterIOSocket implements Runnable {

    private Socket client;
    private Context context;
    private StringBuilder listData = new StringBuilder();
    private TimerTask timerTaskBtRecv;
    private Timer timerBtRecv = new Timer();
    public static BufferedOutputStream out;
    BufferedInputStream in;

    public ThreadReadWriterIOSocket(Context context, Socket client) {
        this.client = client;
        this.context = context;
    }

    public void close() {
        try {
            if (client != null) {
                Log.e(SoketService.TAG, Thread.currentThread().getName()
                        + "--client.close()");
                Intent intent = new Intent(SoketOrder.CLOSE);
                context.sendBroadcast(intent);
                client.close();
            }
        } catch (Exception e) {
            Log.e(SoketService.TAG, Thread.currentThread().getName()
                    + "--read write error");
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Log.e(SoketService.TAG, "a client has connected to server!");
        /*pc端发来的数据msg*/
        String currCMD = "";
        try {
            out = new BufferedOutputStream(client.getOutputStream());
            in = new BufferedInputStream(client.getInputStream());
            SoketService.ioThreadFlag = true;
            while (SoketService.ioThreadFlag) {
                readCMDFromSocket(in);
            }
            out.close();
            in.close();
        } catch (final Exception e) {
            Log.e(SoketService.TAG, Thread.currentThread().getName() + e);
        } finally {
            try {
                if (client != null) {
                    Log.e(SoketService.TAG, Thread.currentThread().getName()
                            + "--client.close()");
                    Intent intent = new Intent(SoketOrder.CLOSE);
                    context.sendBroadcast(intent);
                    client.close();
                }
            } catch (Exception e) {
                Log.e(SoketService.TAG, Thread.currentThread().getName()
                        + "--read write error");
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取命令
     *
     * @param in
     * @return
     */
    private void readCMDFromSocket(BufferedInputStream in) throws IOException {
        int MAX_BUFFER_BYTES = 2048 * 10 * 10;
        byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];

        int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
        listData.append(new String(tempbuffer, 0, numReadedBytes, "UTF-8"));
        resetTimer();
    }

    private void resetTimer() {
        if (timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        timerTaskBtRecv = new TimerTask() {
            @Override
            public void run() {
                try {
                    SoketOrder soketOrder = new Gson().fromJson(listData.toString(), SoketOrder.class);
                    listData = new StringBuilder();
                    //采集指纹
                    if (soketOrder.getResult().equals(SoketOrder.CollectionFinger)) {
                        Intent intent = new Intent(SoketOrder.CollectionFinger);
                        intent.putExtra(ServiceBroadcastReceiver.RECVCOLLECTIONFINGERORDER, new Gson().toJson(soketOrder.getData()));
                        context.sendBroadcast(intent);
                    } else if (soketOrder.getResult().equals(SoketOrder.PUTMANAGERFINGER)) {
                        //管理员指纹验证
                        String ManeData = new Gson().toJson(soketOrder.getData());
                        Intent intent = new Intent(SoketOrder.PUTMANAGERFINGER);
                        intent.putExtra(ServiceBroadcastReceiver.RECVCOLLECTIONFINGERORDER, ManeData);
                        FileUtils.writeTxtToFile(ManeData, FingerHelper.TASTDIR, FingerHelper.MANAFIGER);
                        context.sendBroadcast(intent);
                    } else if (soketOrder.getResult().equals(SoketOrder.DOWNLOADTASK)) {
                        //下载任务
                        Intent intent = new Intent(SoketOrder.DOWNLOADTASK);
                        //清除数据
                        FileUtils.writeTxtToFile(new Gson().toJson(soketOrder.getData()).toString(), FingerHelper.TASTDIR, FingerHelper.TASKPATH);
                        new SharedPreferencesHelper().putSharedPreference(context, FingerHelper.TMEMPTASK, "[]");

                        SoketOrder order = new SoketOrder();
                        order.setResult(SoketOrder.DOWNLOADTASKDONE);
                        out.write(new Gson().toJson(order).getBytes());
                        out.flush();
                        context.sendBroadcast(intent);
                    } else if (soketOrder.getResult().equals(SoketOrder.DOWNLOADLOG)) {
                        //上传日志
                        List<LockLog> list = FingerHelper.getInStance().dbManager.selector(LockLog.class).orderBy("time", true).findAll();
                        SoketOrder order = new SoketOrder();
                        order.setResult(SoketOrder.DOWNLOADLOG);
                        order.setData(list);
                        out.write(new Gson().toJson(order).getBytes());
                        out.flush();
                        //清空日志
                        FingerHelper.getInStance().dbManager.dropTable(LockLog.class);
                    }
                } catch (Exception ex) {
                    try {
                        Intent intent = new Intent(SoketOrder.CLOSE);
                        context.sendBroadcast(intent);
                        client.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        timerBtRecv.schedule(timerTaskBtRecv, 500);
    }
}
